import socket  # 导入socket库，用于网络通信
import threading  # 导入threading库，用于多线程

# 聊天服务器
class ChatServer:
    def __init__(self, host='127.0.0.1', port=8888):
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind((host, port))
        self.server.listen(5)
        print(f'服务器启动，监听 {host}:{port}')
        self.clients = []

    def broadcast(self, msg, source):
        for client in self.clients:
            if client != source:
                try:
                    client.send(msg)
                except:
                    pass

    def handle_client(self, client):
        while True:
            try:
                msg = client.recv(1024)
                if not msg:
                    break
                self.broadcast(msg, client)
            except:
                break
        client.close()
        self.clients.remove(client)

    def run(self):
        while True:
            client, addr = self.server.accept()
            print(f'新连接：{addr}')
            self.clients.append(client)
            threading.Thread(target=self.handle_client, args=(client,), daemon=True).start()

# 聊天客户端
class ChatClient:
    def __init__(self, host='127.0.0.1', port=8888):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.connect((host, port))
        threading.Thread(target=self.receive, daemon=True).start()

    def receive(self):
        while True:
            try:
                msg = self.client.recv(1024)
                if msg:
                    print('\n收到消息：', msg.decode())
            except:
                break

    def send(self, msg):
        self.client.send(msg.encode())

if __name__ == '__main__':
    mode = input('输入 s 启动服务器，输入 c 启动客户端：')
    if mode == 's':
        ChatServer().run()
    else:
        client = ChatClient()
        print('输入消息回车发送，Ctrl+C 退出')
        while True:
            try:
                msg = input()
                client.send(msg)
            except KeyboardInterrupt:
                print('\n已退出')
                break 